package com.xchb.im.conne.init;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.UUID;

/**
 * @author XDD
 * @project muchat
 * @date 2021/7/23
 * @description Good Good Study,Day Day Up.
 */
@Component
@Slf4j
public class Zkinit implements ApplicationListener<ApplicationStartedEvent> {



    @Value("${app.ws.port}")
    private Integer wsPort;

    @Value("${app.zk.addreess}")
    private String zk_address;

    @Value("${app.zk.path}")
    private String path;



    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        CuratorFramework client = CuratorFrameworkFactory.newClient(zk_address,
                new RetryNTimes(10, 5000));
        client.start();

        if(client.checkExists().forPath(path)==null){
            client.create().forPath(path);
        }
        String info = InetAddress.getLocalHost().getHostAddress()+":"+wsPort;
        String nodePath = path+"/"+info;
        if(client.checkExists().forPath(nodePath)!=null){
            client.delete().forPath(nodePath);
        }

        client.create().withMode(CreateMode.EPHEMERAL).forPath(path+"/"+info);

        log.info("zk注册完毕");
    }
}
